#include "stdafx.h"
#include "Anim.h"

Anim::Anim(const char* image, int frames, float time) : frames(frames), time(time),
	activeFrame(0), timer(0.f), flipped(false)
{
	text.loadFromFile(image);
	sprite.setTexture(text, true);
	frameH = text.getSize().y;
	frameW = text.getSize().x / frames;
	sprite.setOrigin(frameW * 0.5f, frameH * 0.5f);

	SetFrame();
}

void Anim::Step(bool flip)
{
	if (flip != flipped)
	{
		flipped = flip;
		SetFrame();
	}

	if (frames)
	{
		if (timer >= time / (float)frames)
		{
			if (++activeFrame == frames)
				activeFrame = 0;

			SetFrame();
			timer = 0.f;
		}
		else
			timer += DELTA;
	}
}

void Anim::Draw(sf::RenderWindow& window, sf::Vector2f& pos, int alpha)
{
	sprite.setColor(sf::Color(255,255,255,alpha));
	sprite.setPosition(pos);
	window.draw(sprite);
}

void Anim::SetFrame()
{
	if (flipped)
		sprite.setTextureRect(sf::IntRect(frameW * activeFrame + frameW, 0, -frameW, frameH));
	else
		sprite.setTextureRect(sf::IntRect(frameW * activeFrame, 0, frameW, frameH));
}

void Anim::Reset()
{
	timer = .0f;
	activeFrame = 0;
	SetFrame();
}